<?php

namespace app\admin\controller\box;

use fast\QRcode;
use app\common\controller\Backend;
use ZipArchive;

/**
 * 盒子
 *
 * @icon fa fa-circle-o
 */
class Box extends Backend {

    /**
     * Box模型对象
     * @var \app\admin\model\Box
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Box;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, [], ['box_id' => 'fa_box.box_id', 'status' => 'fa_box.status', 'box_no' => 'fa_box.box_no', 'user_id' => 'fa_user_box.user_id', 'createtime' => 'fa_box.createtime','province'=>'fa_user_box.province','city'=>'fa_user_box.city','area'=>'fa_user_box.area','quarters_id'=>'fa_user_box.quarters_id','unit_id'=>'fa_user_box.unit_id','room_id'=>'fa_user_box.room_id']);

            $admin_info = db('admin')->where('id', $this->auth->id)->find();
            $admin_where = [];

            if ($admin_info['identity'] == 1) {
                if ($admin_info['province'] != 0) {
                    $admin_where['fa_user_box.province'] = $admin_info['province'];
                }
                if ($admin_info['city'] != 0) {
                    $admin_where['fa_user_box.city'] = $admin_info['city'];
                }
                if ($admin_info['area'] != 0) {
                    $admin_where['fa_user_box.area'] = $admin_info['area'];
                }
                if ($admin_info['quarters_id'] != 0) {
                    $admin_where['fa_user_box.quarters_id'] = $admin_info['quarters_id'];
                }
                if ($admin_info['unit_id'] != 0) {
                    $admin_where['fa_user_box.unit_id'] = $admin_info['unit_id'];
                }
                if ($admin_info['room_id'] != 0) {
                    $admin_where['fa_user_box.room_id'] = $admin_info['room_id'];
                }
            } else if ($admin_info['identity'] == 2) {
                $admin_where['fa_user_box.box_no'] = ['in', $admin_info['box_nos']];
            }
            $total = $this->model
                    ->join('fa_admin', 'fa_box.admin_id = fa_admin.id', 'left')
                    ->join('fa_user_box', 'fa_box.box_id = fa_user_box.box_id and fa_user_box.status = 1 ', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->field('fa_box.*,fa_admin.nickname as admin_name,fa_user_box.user_box_id,fa_user_box.user_id,fa_user_box.province_name,fa_user_box.city_name,fa_user_box.area_name,fa_user_box.quarters_id,fa_user_box.unit_id,fa_user_box.room_id,fa_user_box.contacts,fa_user_box.telephone,fa_user_box.remark,fa_user_box.admin_remark,fa_user_box.place_time_start,fa_user_box.sex')
                    ->join('fa_admin', 'fa_box.admin_id = fa_admin.id', 'left')
                    ->join('fa_user_box', 'fa_box.box_id = fa_user_box.box_id and fa_user_box.status = 1 ', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->order('place_time_start', 'desc')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {

                    if ($val['sex'] == 0) {
                        $val['sex'] = '女';
                    } else {
                        $val['sex'] = '男';
                    }

                    if ($val['status'] == 1) {
                        $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                        $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                        $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
                    }

                    if ($val['status'] == 10) {
                        $val['camp_on_admin'] = db('admin')->where('id', $val['camp_on_admin_id'])->value('nickname');
                    }
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add() {
        if ($this->request->isPost()) {
            $number = $this->request->post("number", 0);
            if ($number <= 0) {
                $this->error('请填写1以上的数字');
            }

            $box_nos = [];
            for ($i = 0; $i < $number; $i++) {

                $data['box_no'] = 'HZ' . substr(date('Ymd', time()), 3) . substr(time(), -3) . rand(100, 999);

                while (in_array($data['box_no'], $box_nos)) {
                    $data['box_no'] = 'HZ' . substr(date('Ymd', time()), 3) . substr(time(), -3) . rand(100, 999);
                }

                $box_nos[] = $data['box_no'];


                $data['admin_id'] = $this->auth->id;

                $this->qrcode($data['box_no']);
                db('box')->insert($data);
            }

            $this->success('添加成功');
        }
        return $this->view->fetch();
    }

    public function allot() {
        $id = $this->request->param('ids');
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");

            $params['province'] = $this->request->post("province", 0);
            $params['city'] = $this->request->post("city", 0);
            $params['area'] = $this->request->post("area", 0);
            $params['quarters_id'] = $this->request->post("quarters", 0);
            $params['unit_id'] = $this->request->post("unit_id", 0);
            $params['room_id'] = $this->request->post("room_id", 0);
            $params['status'] = 30;
            if ($params) {
                $is_add_goods = 0;
                $user_box_info = db('user_box')->where('box_id', 'in', $id)->where('status', 30)->column('user_box_id');

                if ($params['province'] != 0) {
                    $params['province_name'] = db('area')->where('id', $params['province'])->value('name');
                } else {
                    unset($params['province']);
                }

                if ($params['city'] != 0) {
                    $params['city_name'] = db('area')->where('id', $params['city'])->value('name');
                } else {
                    unset($params['city']);
                }

                if ($params['area'] != 0) {
                    $params['area_name'] = db('area')->where('id', $params['area'])->value('name');
                } else {
                    unset($params['area']);
                }

                if ($params['quarters_id'] != 0) {
                    $is_add_goods = 1;
                } else {
                    unset($params['quarters_id']);
                }

                if ($params['user_id'] && $params['room_id'] == 0) {
                    $this->error('请先选择房间');
                }

                if ($params['user_id'] && empty($params['contacts'])) {
                    $this->error('请填写联系人');
                }

                if ($params['user_id'] && empty($params['telephone'])) {
                    $this->error('请填写联系电话');
                }



                $user_box_id = [];
                if ($user_box_info) {
                    db('user_box')->where('user_box_id', 'in', $user_box_info)->update($params);
                    $user_box_id = $user_box_info;
                } else {
                    $box_info = db('box')->where('box_id', 'in', $id)->where('status', 10)->select();

                    if ($box_info) {
                        foreach ($box_info as $box) {
                            $params['box_no'] = $box['box_no'];
                            $params['box_id'] = $box['box_id'];

                            $user_box_id[] = db('user_box')->insertGetId($params);
                        }
                    }
                }
                if ($params['user_id']) {
                    $params['status'] = 1;
                    $params['audit_time'] = date('Y-m-d H:i:s', time());
                    $params['place_time_start'] = date('Y-m-d H:i:s', time());
                    db('box')->where('box_id', 'in', $id)->update(['status' => 1]);
                    db('user_box')->where('box_id', 'in', $id)->where('status', 30)->update($params);

                    //添加库存变动流水
                    $user_box_goods = db('user_box_goods')->where('user_box_id', 'in', $user_box_id)->select();
                    $stock_log['remark'] = '盒子布放初始库存';
                    $stock_log['change_type'] = 0;
                    $stock_log['change_matters'] = 1;
                    foreach ($user_box_goods as $val) {
                        if ($val['stock_num'] > 0) {
                            $stock_log['box_goods_id'] = $val['box_goods_id'];
                            $stock_log['goods_id'] = $val['goods_id'];
                            $stock_log['change_amount'] = $val['stock_num'];
                            $stock_log['quantity'] = $val['stock_num'];
                            db('stock_log')->insert($stock_log);
                        }
                    }
                }

                $this->success('保存成功', null, ['is_add_goods' => $is_add_goods, 'user_box_id' => implode(',', $user_box_id)]);
//                $this->success('分配成功', url('index'));
            } else {
                $this->error('没有需要保存的数据');
            }
        } else {
            $id_sum = count(explode(',', $id));
            $user_box_info = db('user_box')->where('box_id', 'in', $id)->where('status', 30)->find();
//            var_dump($user_box_info);die;
            $is_add_goods = 0;
            $is_have_goods = 0;
            if ($user_box_info) {
                if ($user_box_info['quarters_id'] != 0) {
                    $is_add_goods = 1;
                }
                $user_box_info['room_name'] = db('house')->where(['house_id' => $user_box_info['room_id']])->value('house_name');
                $user_box_info['unit_name'] = db('house')->where(['house_id' => $user_box_info['unit_id']])->value('house_name');
                $user_box_info['quarters_name'] = db('house')->where(['house_id' => $user_box_info['quarters_id']])->value('house_name');

                $user_box_goods = db('user_box_goods')->where('user_box_id', $user_box_info['user_box_id'])->select();

                if ($user_box_goods) {
                    $is_have_goods = 1;
                }
            }

            $user_box_ids = db('user_box')->where('box_id', 'in', $id)->where('status', 30)->column('user_box_id');

            $this->assign('is_have_goods', $is_have_goods);
            $this->assign('is_add_goods', $is_add_goods);
            $this->assign('info', $user_box_info);
            $this->assign('muti', $id_sum);
            $this->assign('user_box_ids', implode(',', $user_box_ids));
            $this->assign('ids', $id);
        }
        return $this->view->fetch();
    }

    public function isyuzan() {
        $id = $this->request->param('ids');

        $user_box_info = db('user_box')->where('box_id', 'in', $id)->where('status', 30)->select();

        $id_sum = count(explode(',', $id));

        $box_sum = count($user_box_info);

        if ($box_sum == 0) {
            $this->success();
        }

        if ($id_sum != $box_sum) {
            $this->error('盒子的状态不同,不允许批量操作');
        }

        $quarters_id = 0;
        $quarters_ids = 0;
        foreach ($user_box_info as $val) {
            $quarters_id = $val['quarters_id'];
            $quarters_ids += $val['quarters_id'];
        }

        if (($quarters_ids / $box_sum) != $quarters_id) {
            $this->error('盒子已分配的小区不同,不允许批量操作!');
        }

        $this->success();
    }

    public function goodslist() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $box_ids = $this->request->param('ids');

            $box_ids = explode(',', $box_ids);
            $user_box_ids = [];
            if (count($box_ids) == 1) {
                $user_box_ids = db('user_box')->where(['box_id' => ['in', $box_ids], 'status' => ['in', ['1', 30]]])->value('user_box_id');
            } else {
                $user_box_ids = db('user_box')->where(['box_id' => ['in', $box_ids], 'status' => 30])->column('user_box_id');
            }

            //获取商品ID
            $goods_ids = db('user_box_goods')->where(['user_box_id' => ['in', $user_box_ids]])->group('goods_id')->column('goods_id');

            $quarters_id = db('user_box')->where(['user_box_id' => ['in', $user_box_ids]])->group('quarters_id')->value('quarters_id');

            $otherwhere[] = ['is_deleted', '=', 0];
            $otherwhere[] = ['goods_id', 'in', $goods_ids];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, $otherwhere, ['is_deleted' => 'fa_goods.is_deleted']);
            $total = db('goods')
                    ->join('fa_goods_brand', 'fa_goods_brand.brand_id = fa_goods.brand_id', 'left')
                    ->join('fa_goods_cate', 'fa_goods_cate.cate_id = fa_goods.cate_id', 'left')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = db('goods')
                    ->field('fa_goods.goods_id,fa_goods.goods_logo,fa_goods.goods_title,fa_goods.goods_model,fa_goods.goods_spec,fa_goods.goods_weight,fa_goods.purchase_price,fa_goods.selling_price as goods_price,fa_goods_brand.brand_title,fa_goods_cate.cate_title')
                    ->join('fa_goods_brand', 'fa_goods_brand.brand_id = fa_goods.brand_id', 'left')
                    ->join('fa_goods_cate', 'fa_goods_cate.cate_id = fa_goods.cate_id', 'left')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {
                    $val['selling_price'] = db('house_goods')->where(['house_id' => $quarters_id, 'goods_id' => $val['goods_id']])->value('selling_price');
                    $user_box_goods = db('user_box_goods')->where(['user_box_id' => ['in', $user_box_ids], 'goods_id' => $val['goods_id']])->find();
                    $val['createtime'] = $user_box_goods['createtime'];
                    $val['stock_num'] = $user_box_goods['stock_num'];
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
//        return $this->view->fetch();
    }

    public function import() {
        return parent::import();
    }

    public function laying() {
        $id = $this->request->param('ids', 0);
        $laying_list = db('user_box')->where(['box_id' => $id, 'status' => 20])->select();

        foreach ($laying_list as &$val) {
            $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
            $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
            $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
        }
        unset($val);
        $this->assign('list', $laying_list);
        return $this->view->fetch();
    }

    public function huishou() {
        $user_box_id = input('user_box_id', 0, 'intval');
        $data['recovery_reason'] = input('recovery_reason');

        if (empty($data['recovery_reason'])) {
            $this->error('请填写回收原因');
        }

        $data['recovery_time_start'] = date('Y-m-d H:i:s');
        $data['place_time_end'] = date('Y-m-d H:i:s');
        $data['status'] = 20;

        $user_box_info = db('user_box')->where(['user_box_id' => $user_box_id])->find();

        db('box')->where(['box_id' => $user_box_info['box_id']])->update(['status' => 0, 'updatetime' => date('Y-m-d H:i:s')]);
        db('user_box')->where(['user_box_id' => $user_box_id])->update($data);
        $this->success();
    }

    public function quxiaoyuzan() {
        $ids = $this->request->param('ids');

        db('box')->where(['box_id' => ['in', $ids]])->update(['status' => 0, 'updatetime' => date('Y-m-d H:i:s'), 'camp_on_time' => '']);
        $this->success();
    }

    public function delbox() {
        $ids = $this->request->param('ids');
        db('box')->where(['box_id' => ['in', $ids]])->delete();
        $this->success();
    }

    public function yuzan() {
        $ids = $this->request->param('ids');

        db('box')->where(['box_id' => ['in', $ids]])->update(['status' => 10, 'camp_on_time' => date('Y-m-d H:i:s'), 'camp_on_admin_id' => $this->auth->id]);
        $this->success();
    }

    //手动生成二维码
    public function updateQrcode() {
        $box_no = input('box_no');

        $this->qrcode($box_no);
    }

    public function exportqrcode() {

        $ids = $this->request->param('ids');

        if (empty($ids)) {
            $this->error('请选择需要导出的消费二维码');
        }

        $fileList = [];

        $box_list = db('box')->where(['box_id' => ['in', $ids]])->select();

        if (empty($box_list)) {
            $this->error('没有找到对应的消费二维码');
        }

        foreach ($box_list as $val) {
            $fileList[] = './uploads/box/' . $val['box_no'] . '.png';
        }

        $zip_name = "box-no-" . date('Y-m-d-H-i-s') . ".zip";
        //打包
        $filename = "./uploads/zip/" . $zip_name;
        $zip = new ZipArchive();
        $zip->open($filename, ZipArchive::CREATE);   //打开压缩包
        foreach ($fileList as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }

        $zip->close();  //关闭压缩包
//        var_dump($this->request);die;
//        echo $this->request->domain().'/mohe/public/uplodas/zip/'.$zip_name;die;
        $this->redirect($this->request->domain() . '/uploads/zip/' . $zip_name, 200);
    }

    /**
     * host 生成链接地址
     * level 容错级别 
     * size 图片大小
     */
    public function qrcode($box_no = '', $level = 3, $size = 10) {

        $errorCorrectionLevel = intval($level); //容错级别 
        $matrixPointSize = intval($size); //生成图片大小 
        $url = 'https://www.mohebianli.com/index/pub/index/box/' . base64_encode($box_no);

        //生成二维码图片 
        $object = new QRcode();
        $fileName = './uploads/box/' . $box_no . '.png';

        $res = $object->png($url, $fileName, $errorCorrectionLevel, $matrixPointSize, 2, false);
//        $QR = imagecreatefromstring(file_get_contents($fileName));
//
//        //输出图片    
//        imagepng($QR, $card_number . '.png');
//        imagedestroy($QR);
        return $fileName;
    }

}
